<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 系统字典</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <div class="handle-box"><span><h3>{{dictHeadTitle}}</h3></span></div>
                <el-tabs v-model="view_tab_activeName" @tab-click="func_dialog_tab_handleClick" >
                    <el-tab-pane v-loading="tabIsLoading" label="字典类目" name="first">
                        <el-card class="box-card" >
                            <el-form :model="dictform" label-width="formLabelWidth">
                                <el-form-item label="字典索引编号" :label-width="formLabelWidth">
                                    <el-input v-model="dictform.groupId" maxlength="10" readonly show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="索引值" :label-width="formLabelWidth">
                                    <el-input v-model="dictform.dicValue" minlength="4" maxlength="4" show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="字典中文名称" :label-width="formLabelWidth">
                                    <el-input v-model="dictform.dicName" maxlength="40" show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="字典类目英文名称" :label-width="formLabelWidth">
                                    <el-input v-model="dictform.groupCode" clearable @blur="func_querySearchAsync"></el-input>
                                </el-form-item>
                                <el-form-item label="字典类目编号" :label-width="formLabelWidth">
                                    <el-input v-model="dictform.groupId" minlength="4" maxlength="4" show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="排序编号" :label-width="formLabelWidth">
                                    <el-select v-model="dictform.sort" placeholder="Select">
                                    <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </el-card>
                        <div class="handle-footer"><el-row>
                            <el-col :span="21"></el-col>
                            <el-col :span="3">
                                <el-button type="primary" icon="el-icon-plugs" @click="func_saveDictData">保存类目数据</el-button>
                            </el-col></el-row>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="字典释义" name="second">
                        <el-card class="box-card">
                            <el-row><div>
                                <el-button type="primary" icon="el-icon-plugs" @click="func_addDialogRowClick">添加一行</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="func_delDialogRowClick">选择删除</el-button>
                            </div></el-row>
                            <el-row><el-table v-loading="isLoading" :data="expTableData" stripe border class="table" ref="multipleTable"
                            @selection-change="(selections)=>{func_handleSelectionChange(selections,'true')}"
                            @select-all="(selections)=>{func_handleSelectionAll(selections,'true')}"
                            header-cell-class-name="table-header" style="width: 100%;margin-top:10px">
                                <el-table-column type="selection" width="50" align="center"/>
                                <el-table-column prop="id" label="ID" />
                                <el-table-column prop="dicCode" label="索引编号" />
                                <el-table-column prop="dicName" label="中文释义" />
                                <el-table-column prop="dicNickname" label="英文释义" />
                                <el-table-column prop="dicValue" label="索引值" />
                                <el-table-column prop="strGroupCode" label="类目名称" />
                                <el-table-column prop="groupCode" label="类目分类" />
                                <el-table-column prop="groupId" label="类目编号" />
                                <el-table-column prop="sort" label="排序" />
                                <el-table-column label="操作" width="180" align="center">
                                <template #default="scope">
                                    <el-button type="text" icon="el-icon-edit" @click="func_handleEdit(scope.$index, scope.row)">编辑</el-button>
                                    <el-button type="text" icon="el-icon-delete" class="red" @click="func_handleDelete(scope.$index, scope.row)">删除</el-button>
                                </template>
                                </el-table-column>
                            </el-table>
                            <div class="pagination">
                                <el-pagination @size-change="func_handleSizeChange" @current-change="func_handlePageChange"
                                background layout="total, sizes, prev, pager, next," 
                                        :current-page="query.pageNum"
                                        :page-sizes=[10,50,100]
                                        :page-size="query.pageSize"
                                        :total="total" >
                                </el-pagination>
                            </div>
                            </el-row>
                        </el-card>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="view_edit_dialog_Visible" width="75%" :close-on-click-modal="false">
            <div class="handle-box"><span><h3>{{dictHeadTitle}}</h3></span></div>
            <el-card class="box-card">
            <el-form :model="dictExpform" label-width="formLabelWidth">
                <!-- <el-form-item label="字典索引编号" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.dicCode" maxlength="10" readonly show-word-limit></el-input>
                </el-form-item> -->
                <el-form-item label="索引值" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.dicValue" minlength="4" maxlength="4" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="释义中文名称" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.dicName" maxlength="40" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="释义英文名称" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.dicNickname" maxlength="40" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="类目英文名称" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.groupCode" readonly></el-input>
                </el-form-item>
                <!-- <el-form-item label="所属类目" v-if="view_detail_show" :label-width="formLabelWidth">
                    <el-select v-model="dictExpform.groupId" placeholder="请选择所属类目">
                        <el-option v-for="item in groupPopOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="类目编号" :label-width="formLabelWidth">
                    <el-input v-model="dictExpform.groupId" minlength="4" maxlength="4" readonly show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="排序编号" :label-width="formLabelWidth">
                    <el-select v-model="dictExpform.sort" placeholder="Select">
                        <el-option v-for="item in 10" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
            </el-form></el-card>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="view_edit_dialog_Visible = false">取 消</el-button>
                    <el-button type="primary" @click="func_addDialogRow">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchDictionaryData, fetchDictionaryOneData, 
fetchDictionaryPopData, fetchDictionaryExpData, tlEditDict, tlAddDictExpRow, tlDelDict } from "../../api/dict.js";
import { SUCCMESS_DIALOG_MESSAGE, ERROR_CHOOSE_DEL_DICTIONARY_EMPTY} from "../../api/messages";
export default defineComponent({
    name: "basetable",
    components: {
        vDictSelector,
    },
    setup() {
        // 表单输入框前长度
        const formLabelWidth = ref("170px");
        let dictHeadTitle = ref("新建字典类目");
        let idx = -1;
        // 默认显示标签
        let view_tab_activeName=ref('first');
        // 类目释义表查询条件
        const query = ref({
            dictCode: "",
            pageNum: 1,
            pageSize: 10,
            activeStatus: 0,
        });
        // 类目释义表总数量
        const total = ref(0);
        // 表单loading: true,
        const isLoading = ref(true);
        const tabIsLoading = ref(false);
        // 表格编辑时弹窗和保存
        const view_edit_dialog_Visible = ref(false);
        // 类目编辑表单
        const dictform = reactive({
            id: 0,
            parentId: 0,
            dicCode: "",
            dicName: "",
            dicValue: "",
            groupCode: "",
            groupId: "",
            sort: 1,
            disable:0,
            deleteFlag:0,
            children: [{}],
        });
        // 类目释义编辑表单
        const dictExpform = reactive({
            id: 0,
            dicCode: "",
            dicName: "",
            dicNickname: "",
            dicValue: "",
            strGroupCode: "",
            groupCode: "",
            groupId: "",
            sort: 1,
        });
        // 类目下拉选单
        let groupPopOptions = ref([]);
        // 类目释义表格
        const expTableData = ref([]);
        /**
         * 标签切换方法
         */
        const func_dialog_tab_handleClick = (tab, event) =>{
            if(tab.index == 1 ){
                isLoading.value = true;
                expTableData.value= [];
                func_getData(query);
            } else {
                isLoading.value = false;
            }
        };
        // 推荐输入框 ----------------------------------------------------------------START
        const func_querySearchAsync = () =>{
            tabIsLoading.value = true;
            var _query = {groupCode:dictform.groupCode};
            var t = setTimeout(function() {
                fetchDictionaryOneData(_query).then((res)=>{
                    var obj = res.data.data;
                    if(obj != null && JSON.stringify(obj) != '{}'){
                        Object.keys(obj).forEach((item) => {
                            dictform[item] = obj[item];
                        });
                    }else{
                        Object.keys(dictform).forEach((item) => {
                            dictform[item] = '';
                        });
                        dictform.groupCode = _query.groupCode;
                    }
                    tabIsLoading.value = false;
                }).catch(()=>{tabIsLoading.value = false;});
            },1000);
            
        };
        // 推荐输入框 ----------------------------------------------------------------END
        /**
         * 词典释义读取方法
         * 标签切换到释义信息时候加载读取类目下的释义数据
         */
        const func_getData = (query) =>{
            // 判定表单的类目识别ID
            if(Object.keys(""+dictform.groupId).length > 0) {
                query.dictCode = dictform.groupId;
                // 刷新释义表数据
                var t= setTimeout(function() {
                    fetchDictionaryExpData(query).then((res) =>{
                        expTableData.value = res.data.data.list;
                        total.value = res.data.data.total;
                        isLoading.value = false;
                    }).catch(() => { isLoading.value = false;});
                },1000);
            } else {
                ElMessage.warning("请输入字典类目数据编号");
                isLoading.value = false;
            }
        };
        /**
         * @name 分页导航
         */
        const func_handlePageChange = (val) => {
            isLoading.value = true;
            query.pageNum = val;
            func_getData(query);
        };
        /**
         * @name 分页数量查询
         */
        const func_handleSizeChange = (val) => {
            isLoading.value = true;
            query.pageNum = 1;
            query.pageSize = val;
            func_getData(query);
        }; 
        // 公共 数据表多选临时存储
        let multipleTable = ref([]);
        let multipleSelectData =reactive([]);
        /**
         * @name 公共 列表内选择数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionChange = (selections,param) => {
            multipleSelectData = selections;
        };
        /**
         * @name 公共 列表内全选数据
         * @description 勾选的回调函数，返回全部勾选值
         */
        const func_handleSelectionAll = (selections,param) => {
            multipleSelectData = selections;
        };
        /**
         * 列表内编辑行数据
         */
        const func_handleEdit = (index, row) => {
            idx = index;
            Object.keys(dictExpform).forEach((item) => {
                dictExpform[item] = row[item];
            });
            view_edit_dialog_Visible.value = true;
        };
        /**
         * 删除行数据
         */
        const func_handleDelete = (index, row) => {
            // 二次确认删除
            ElMessageBox.confirm("确定要删除吗？", "提示", {
                type: "warning",
            })
            .then(() => {
                isLoading.value= true;
                let _v = [row.id];
                func_delDictData(_v);
            })
            .catch(() => {});
        };
        /**
         * 添加一行类目释义
         */
        const func_addDialogRowClick = () =>{
            Object.keys(dictExpform).forEach((item) => {
                dictExpform[item] = "";
            });
            dictExpform.strGroupCode = dictform.dicName;
            dictExpform.groupCode = dictform.groupCode;
            dictExpform.groupId = dictform.groupId;
            view_edit_dialog_Visible.value=true;
        };
        /**
         * 删除选择行数据
         */
        const func_delDialogRowClick = () =>{
            if(multipleSelectData.length ===0) {
                ElMessage.warning(ERROR_CHOOSE_DEL_DICTIONARY_EMPTY);
                return;
            }
            let _v = multipleSelectData;
            func_delDialogRow(_v);
        };
        /**
         * 推送编辑数据到服务
         */
        const func_addDialogRow = () =>{
            isLoading.value= true;
            if(idx < 0){
                // 编辑数据到行
                expTableData.value.push({
                    id: 0,
                    dicCode: dictExpform.groupId + '' +dictExpform.dicValue,
                    dicName: dictExpform.dicName,
                    dicNickname: dictExpform.dicNickname,
                    dicValue: dictExpform.dicValue,
                    strGroupCode: dictform.dicName,
                    groupCode: dictExpform.groupCode,
                    groupId: dictExpform.groupId,
                    sort: dictExpform.sort,
                });
                dictExpform.dicCode = dictExpform.groupId + '' +dictExpform.dicValue;
                // 推送编辑数据到服务
                tlAddDictExpRow(dictExpform).then((res) =>{
                    if(res.data.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                    }
                }).catch(() => {});
            } else {
                // 推送编辑数据到服务
                tlEditDict(dictExpform).then((res) =>{
                    if(res.data.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        ElMessage.success(`修改第 ${idx + 1} 行成功`);
                    }
                }).catch(() => {});
            }
            // 刷新释义表数据
            func_getData(query);
            view_edit_dialog_Visible.value=false;
            idx = -1;
        };
        const func_delDialogRow = (_data) => {
            // 二次确认删除
            ElMessageBox.confirm("确定要删除吗？", "提示", {
            type: "warning",
            }).then(() => {
                var _v = _data.map((item) => item.id);
                func_delDictData(_v);
            }).catch(() => {});
        };
        /**
         * 保存字典数据
         */
        const func_saveDictData = () => {
            dictform.children = null;
            tlEditDict(dictform).then((res) =>{
                if(res.data.code != 200) {
                    if(res.type == 0) {
                        ElMessage.warning(res.data.msg);
                    } else {
                        ElMessage.error(res.data.msg);
                    }
                } else {
                    ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                }
            }).catch(() => {});
        };
        const func_delDictData = (_v) => {
            var t = setTimeout(() => {
                tlDelDict(_v).then((res) => {
                    if(res.data.code != 200) {
                        if(res.type == 0) {
                            ElMessage.warning(res.data.msg);
                        } else {
                            ElMessage.error(res.data.msg);
                        }
                    } else {
                        ElMessage.success(SUCCMESS_DIALOG_MESSAGE);
                        // 刷新释义表数据
                        func_getData(query);
                    }
                });
            }, 1000);
        };
        const rules = {
            groupId: [
                { required: true, message: "请输入字典编号", trigger: "blur" },
            ],
        };
        return {
            dictHeadTitle, formLabelWidth, view_tab_activeName,
            query, total, isLoading, tabIsLoading,
            view_edit_dialog_Visible, dictform, dictExpform, expTableData, groupPopOptions,
            func_getData, func_handlePageChange, func_handleSizeChange,
            multipleTable, multipleSelectData,
            func_handleSelectionAll, func_handleSelectionChange, func_querySearchAsync,
            func_handleEdit, func_handleDelete, func_dialog_tab_handleClick,
            func_addDialogRowClick, func_delDialogRowClick, func_addDialogRow, func_delDialogRow,
            func_saveDictData, func_delDictData,
            rules,
        };
    },
})
</script>

<style scoped>
.form-box {
    width: 100%;
}
.handle-box {
    margin-bottom: 20px;
}
.handle-footer {
    margin-top: 20px;
}
.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}

.tabDialog {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.box-card {
    width: 99%;
    /* height:450px;
    overflow-y:auto;
    overflow-x:hidden; */
}
.box-card.button {
    padding: 0;
    float: right;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>